﻿Imports Equipment.Core
Imports Equipment.DataAccess
Imports Equipment.Business
Imports Equipment.Model

Namespace Equipment
    <RequiresPageAcces(Page:=PageType.NotificationType)> _
    Public Class NotificationController
        Inherits System.Web.Mvc.Controller

        '
        ' GET: /Notification

        Function Index() As ActionResult
            ViewData("Role") = New SelectList(Role.RetrieveAll(), "ID", "Description")
            ViewData("Notifications") = Notification.RetrieveAll()
            ViewData("EntityType") = EntityType.Notification
            Return View()
        End Function

        '
        ' GET: /Notification/Details/5

        Function Details(ByVal id As Integer) As ActionResult
            Return View()
        End Function

        '
        ' GET: /Notification/Create

        Function Create() As ActionResult
            InitControls(0, String.Empty, NotificationTrigger.Asset_Create, NotificationOverdueType.EveryXAfterOverdue, 0, Nothing)
            Return View()
        End Function

        '
        ' POST: /Notification/Create

        <HttpPost()> _
        Function Create(ByVal collection As FormCollection) As ActionResult
            Dim roles = Role.RetrieveAll()
            Dim notoficationName As String = collection("NotificationName")
            Dim changeDetails As New List(Of String)
            Try
                Dim trigger As NotificationTrigger = [Enum].Parse(GetType(NotificationTrigger), collection("Trigger"))
                Dim overdueType As NotificationOverdueType = [Enum].Parse(GetType(NotificationOverdueType), collection("rbOverdueType"))

                If String.IsNullOrEmpty(notoficationName) Then
                    ModelState.AddModelError("NotificationName", "Notification Name is required.")
                End If

                Dim newNotification As New Notification()
                newNotification.Description = notoficationName
                newNotification.OverdueType = overdueType
                newNotification.OverdueXValue = 0
                newNotification.NotificationTrigger = trigger


                If Not String.IsNullOrEmpty(notoficationName) Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Notofication Name", notoficationName))
                End If

                changeDetails.Add(String.Format(Constants.UI.FIELD_SET_TEMPLATE, "Trigger", trigger.ToString()))

                'If trigger = NotificationTrigger.WorkOrder_Overdue Then
                '    Select Case overdueType
                '        Case NotificationOverdueType.EveryXDaysAfterOverdue
                '            newNotification.OverdueXValue = Integer.Parse(collection("txtEveryXDaysAfterOverdue"))
                '        Case NotificationOverdueType.XDaysBeforeOverdue
                '            newNotification.OverdueXValue = Integer.Parse(collection("txtXDaysBeforeOverdue"))
                '        Case NotificationOverdueType.XHoursBeforeOverdue
                '            newNotification.OverdueXValue = Integer.Parse(collection("txtXHoursBeforeOverdue"))
                '        Case Else
                '            newNotification.OverdueXValue = 0
                '    End Select
                'End If

                For Each role As Role In roles
                    Dim selectedRole As Boolean = Boolean.Parse(CStr(collection(String.Format("cbxRole_{0}", role.ID))).Split(",")(0))
                    If selectedRole Then
                        newNotification.Roles.Add(role)
                    End If
                Next

                If newNotification.Roles.Count = 0 Then
                    ModelState.AddModelError("Roles", "At least one of the roles has to be selected.")
                End If

                'If Not ModelState.IsValid Then
                '    InitControls(0, notoficationName, NotificationTrigger.Asset_Create, NotificationOverdueType.EveryXDaysAfterOverdue, 0, newNotification.Roles)
                '    Return View()
                'End If


                Notification.Insert(newNotification)
                ModificationHistory.Insert(EntityType.Notification, notoficationName, ModificationAction.Created, Application.CurrentUserInfo.UserID, changeDetails, newNotification.ID)
                NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.Notification_Create, notoficationName)

                Return RedirectToAction("Index")
            Catch
                'InitControls(0, notoficationName, NotificationTrigger.Asset_Create, NotificationOverdueType.EveryXDaysAfterOverdue, 0, Nothing)
                Return View()
            End Try
        End Function

        Function Edit(ByVal id As Integer) As ActionResult
            Dim notificationTypeToEdit As Notification = Notification.GetByPrimaryKey(id)

            If notificationTypeToEdit IsNot Nothing Then
                InitControls(notificationTypeToEdit.ID, notificationTypeToEdit.Description, notificationTypeToEdit.NotificationTrigger, _
                             notificationTypeToEdit.OverdueType, notificationTypeToEdit.OverdueXValue, notificationTypeToEdit.Roles)
            End If

            Return View()
        End Function

        <HttpPost()> _
        Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
            Dim roles = Role.RetrieveAll()
            Dim notificationTypeToEdit As Notification = Notification.GetByPrimaryKey(id)
            Dim changeDetails As New List(Of String)

            Try
                Dim oldXValue As Integer = 0
                Dim notoficationName As String = collection("NotificationName")
                Dim trigger As NotificationTrigger = [Enum].Parse(GetType(NotificationTrigger), collection("Trigger"))
                Dim overdueType As NotificationOverdueType = [Enum].Parse(GetType(NotificationOverdueType), collection("rbOverdueType"))

                If String.IsNullOrEmpty(notoficationName) Then
                    ModelState.AddModelError("NotificationName", "Notification Name is required.")
                End If

                If notificationTypeToEdit.Description <> notoficationName Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Description", notificationTypeToEdit.Description, notoficationName))
                End If

                If notificationTypeToEdit.NotificationTrigger <> trigger Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Trigger", notificationTypeToEdit.NotificationTrigger, trigger))
                End If

                If notificationTypeToEdit.OverdueType <> overdueType Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "Overdue", notificationTypeToEdit.OverdueType, overdueType))
                End If

                If notificationTypeToEdit.OverdueXValue.HasValue Then
                    oldXValue = notificationTypeToEdit.OverdueXValue.Value
                End If

                notificationTypeToEdit.Description = notoficationName
                notificationTypeToEdit.OverdueType = overdueType
                notificationTypeToEdit.NotificationTrigger = trigger

                'If trigger = NotificationTrigger.WorkOrder_Overdue Then
                '    Select Case overdueType
                '        Case NotificationOverdueType.EveryXDaysAfterOverdue
                '            notificationTypeToEdit.OverdueXValue = Integer.Parse(collection("txtEveryXDaysAfterOverdue"))
                '        Case NotificationOverdueType.XDaysBeforeOverdue
                '            notificationTypeToEdit.OverdueXValue = Integer.Parse(collection("txtXDaysBeforeOverdue"))
                '        Case NotificationOverdueType.XHoursBeforeOverdue
                '            notificationTypeToEdit.OverdueXValue = Integer.Parse(collection("txtXHoursBeforeOverdue"))
                '        Case Else
                '            notificationTypeToEdit.OverdueXValue = 0
                '    End Select
                'End If

                If notificationTypeToEdit.OverdueXValue.Value <> oldXValue Then
                    changeDetails.Add(String.Format(Constants.UI.FIELD_MODIFICATION_TEMPLATE, "X Value", oldXValue, notificationTypeToEdit.OverdueXValue))
                End If

                Dim existingRoleIDs = notificationTypeToEdit.Roles.ToDictionary(Function(r) r.ID)

                notificationTypeToEdit.Roles.Clear()

                For Each role As Role In roles
                    Dim selectedRole As Boolean = Boolean.Parse(CStr(collection(String.Format("cbxRole_{0}", role.ID))).Split(",")(0))
                    If selectedRole Then
                        notificationTypeToEdit.Roles.Add(role)
                    End If
                    If selectedRole Then
                        If Not existingRoleIDs.ContainsKey(role.ID) Then
                            changeDetails.Add(String.Format("Added role '{0}'", role.Description))
                        End If
                    Else
                        If existingRoleIDs.ContainsKey(role.ID) Then
                            changeDetails.Add(String.Format("Deleted role '{0}'", role.Description))
                        End If
                    End If
                Next

                If notificationTypeToEdit.Roles.Count = 0 Then
                    ModelState.AddModelError("Roles", "At least one of the roles has to be selected.")
                End If

                If Not ModelState.IsValid Then
                    'InitControls(notificationTypeToEdit.ID, notificationTypeToEdit.Description, NotificationTrigger.Asset_Create, _
                    '                NotificationOverdueType.EveryXDaysAfterOverdue, 0, notificationTypeToEdit.Roles)
                    Return View()
                End If


                notificationTypeToEdit.Save()
                ModificationHistory.Insert(EntityType.Notification, notificationTypeToEdit.Description, ModificationAction.Modified, Application.CurrentUserInfo.UserID, changeDetails, notificationTypeToEdit.ID)
                NotificationManager.CreateNotificationsByTrigger(NotificationTrigger.Notification_Modify, notificationTypeToEdit.Description)

                Return RedirectToAction("Index")
            Catch
                'InitControls(notificationTypeToEdit.ID, notificationTypeToEdit.Description, NotificationTrigger.Asset_Create, _
                '                NotificationOverdueType.EveryXDaysAfterOverdue, 0, notificationTypeToEdit.Roles)
                Return View()
            End Try
        End Function


#Region "AJAX"
        <HttpPost()> _
        Function FilterNotification(ByVal roleID As Integer?) As ActionResult
            If Not roleID.HasValue Then
                roleID = 0
            End If

            Dim notifications As IEnumerable(Of Notification)
            If roleID > 0 Then
                notifications = Notification.RetrieveAllByRoleID(roleID)
            Else
                notifications = Notification.RetrieveAll()
            End If

            ViewData("Notifications") = notifications

            Return PartialView("~/Views/Notification/Controls/NotificationGrid.ascx")
        End Function
#End Region

#Region "Private Section"
        Private Sub InitControls(ByVal selectedNotificationID As Integer, ByVal selectedNotificationName As String, _
                                    ByVal selectedNotificationTrigger As NotificationTrigger, ByVal selectedOverdueType As NotificationOverdueType, _
                                            ByVal selectedOverdueXValue As Integer, ByVal selectedRoles As List(Of Role))

            Dim overdueTypes = NotificationOverdueLookup.RetrieveAll()
            For Each overdue In overdueTypes
                If overdue.Type = selectedOverdueType Then
                    overdue.Selected = True
                End If
            Next

            ViewData("ID") = selectedNotificationID
            ViewData("NotificationName") = selectedNotificationName

            'If selectedNotificationTrigger = NotificationTrigger.WorkOrder_Overdue Then
            '    ViewData("ShowOverdueTable") = True
            'End If

            ViewData("Trigger") = New SelectList(NotificationTriggerLookup.RetrieveAll(), "Type", "Description", selectedNotificationTrigger)
            ViewData("OverdueTypes") = overdueTypes
            ViewData("SelectedOverdueValue") = selectedOverdueXValue
            ViewData("Roles") = Role.RetrieveAll()

            If selectedRoles IsNot Nothing Then
                For Each role As Role In selectedRoles
                    ViewData(String.Format("SelectedRole_{0}", role.ID)) = True
                Next
            End If
        End Sub
#End Region

    End Class
End Namespace